<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="process-history-container">
          <div class="page-header">
            <h2>生产记录管理</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索工序名称"
                clearable
                class="search-input"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="handleSearch">
                <el-option label="进行中" value="进行中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已取消" value="已取消" />
              </el-select>
            </div>
          </div>

          <!-- 生产记录列表 -->
          <el-table :data="histories" border style="width: 100%" v-loading="loading">
            <el-table-column prop="historyId" label="记录ID" width="80" />
            <el-table-column prop="taskId" label="任务ID" width="80" />
            <el-table-column prop="processName" label="工序名称" width="120" />
            <el-table-column label="开始时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column label="结束时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="yieldRate" label="良品率(%)" width="100">
              <template #default="scope">
                {{ scope.row.yieldRate.toFixed(2) }}%
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="记录时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.recordTime) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getProcessHistories,
  getProcessHistoryById,
  addProcessHistory,
  updateProcessHistory,
  deleteProcessHistory
} from '@/api/production'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Plus, Edit, Delete, Warning } from '@element-plus/icons-vue'

// 数据定义
const histories = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEdit = ref(false)
const currentHistory = ref(null)
const historyFormRef = ref(null)

// 表单数据
const historyForm = reactive({
  historyId: null,
  taskId: null,
  processName: '',
  startTime: null,
  endTime: null,
  yieldRate: 0,
  status: '进行中',
  recordTime: null
})

// 表单验证规则
const rules = {
  taskId: [
    { required: true, message: '请输入任务ID', trigger: 'blur' },
    { type: 'number', message: '任务ID必须为数字', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '请选择工序名称', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  yieldRate: [
    { required: true, message: '请输入良品率', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '良品率必须在0-100之间', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取生产记录列表
const fetchHistories = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }

    // 如果有状态筛选，添加到参数中
    if (filterStatus.value) {
      params.status = filterStatus.value
    }

    const res = await getProcessHistories(params)

    if (res.success) {
      histories.value = res.data.records || res.data
      total.value = res.data.total || res.data.length
    } else {
      ElMessage.error(res.message || '获取生产记录失败')
    }
  } catch (error) {
    console.error('获取生产记录失败:', error)
    ElMessage.error('获取生产记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchHistories()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchHistories()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchHistories()
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(historyForm, {
    historyId: null,
    taskId: null,
    processName: '',
    startTime: new Date(),
    endTime: null,
    yieldRate: 0,
    status: '进行中',
    recordTime: new Date()
  })
  dialogVisible.value = true
}


// 确认删除
const confirmDelete = async () => {
  if (!currentHistory.value || !currentHistory.value.historyId) return

  try {
    const res = await deleteProcessHistory(currentHistory.value.historyId)

    if (res.success) {
      ElMessage.success(`生产记录已成功删除`)
      deleteDialogVisible.value = false
      await fetchHistories()
    } else {
      ElMessage.error(res.message || '删除生产记录失败')
    }
  } catch (error) {
    console.error('删除生产记录失败:', error)
    ElMessage.error('删除生产记录失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!historyFormRef.value) return

  await historyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (isEdit.value) {
          // 编辑记录
          res = await updateProcessHistory(historyForm)
        } else {
          // 添加记录
          res = await addProcessHistory(historyForm)
        }

        if (res.success) {
          const message = isEdit.value ? '编辑' : '添加'
          ElMessage.success(`生产记录${message}成功`)
          dialogVisible.value = false
          fetchHistories()
        } else {
          ElMessage.error(res.message || `生产记录${isEdit.value ? '编辑' : '添加'}失败`)
        }
      } catch (error) {
        console.error(`生产记录${isEdit.value ? '编辑' : '添加'}失败:`, error)
        ElMessage.error(`生产记录${isEdit.value ? '编辑' : '添加'}失败`)
      }
    }
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '进行中':
      return 'warning'
    case '已完成':
      return 'success'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHistories()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.process-history-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #F56C6C;
}
</style>
